from django.contrib.auth.decorators import login_required
from django.core.serializers import json
from django.db.models import Q
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from odf.text import P

from carts.models import Cart
from goods.models import Goods


# 添加到购物车
@csrf_exempt
@login_required(login_url='/user_login/')
def add(request):
    user = request.user
    goods_id = request.POST.get('goods_id')
    count = request.POST.get('count')
    print('商品编号是：', goods_id, count)

    cart = Cart()
    cart.c_goods_id = goods_id
    cart.c_count = count
    cart.c_user = user
    cart.save()
    return JsonResponse({'res': 1})


# 购物车展示
@login_required(login_url='/user_login/')
def cart(request):
    # 一个商品的价格  =   购物车里的件数  X   商品每kg的价格（price）
    user = request.user
    # 获取用户的所有购物车
    data = Cart.objects.filter(c_user=user).all()
    sum = 0
    sumprice = 0
    amount = 0
    for i in data:
        amount = i.c_count * i.c_goods.price
        # 动态增加属性
        i.amount = amount
        sum += i.c_count
        sumprice += i.amount
    return render(request, 'cart.html', {'data': data, 'sum': sum, 'sumprice': sumprice})


# 更新购物车
@csrf_exempt
@login_required(login_url='/user_login/')
def update_cart(request):
    user = request.user
    if request.method == 'POST':
        count = int(request.POST.get("count"))
        cart_id = int(request.POST.get('cart_id'))
        this_cart = Cart.objects.get(id=cart_id)
        if count > this_cart.c_count:
            return JsonResponse({'res': '已超过库存'})
        else:
            this_cart.c_count = count
            this_cart.save()
            # 统计购物车中的总件数
            all_c = 0
            all_cart_count = Cart.objects.filter(c_user=user)
            for c in all_cart_count:
                all_c += c.c_count
            return JsonResponse({'res': 1, 'all_c': all_c})
    else:
        return JsonResponse({'res': 2})


# 删除购物车
@csrf_exempt
@login_required(login_url='/user_login/')
def cart_delete(request):
    user = request.user
    cart_id = request.POST.get('cart_id')
    cart = Cart.objects.get(id=cart_id)
    cart.delete()
    return JsonResponse({'res': 1})
